import { get } from "../../utils/request";
Page({
  data: {
    tabs: ["vue", "react", "typescript", "html", "css", "node"],
    currentIndex: 0,
    interviews: [],
    swiperHeight: 150,
    playingId: -1,
    audioManager: null,
  },
  changeCurrentIndex(currentIndex) {
    this.setData({ currentIndex }, this.getInterviews);
  },
  tabChange(event) {
    this.changeCurrentIndex(event.currentTarget.dataset["index"]);
  },
  swiperChange(event) {
    this.changeCurrentIndex(event.detail.current);
  },
  async getInterviews() {
    let type = this.data.tabs[this.data.currentIndex];
    const { interview: interviews } = await get("/interview", {
      data: { type },
    });
    this.setData(
      {
        interviews,
      },
      () => {
        const query = wx.createSelectorQuery();
        query
          .select(`.swiper-item-${this.data.currentIndex}`)
          .boundingClientRect();
        query.exec((result) => {
          const { height } = result[0];
          this.setData({
            swiperHeight: height,
          });
        });
      }
    );
  },
  async onLoad() {
    this.getInterviews();
    this.initAudioManager();
  },
  initAudioManager() {
    const audioManager = wx.getBackgroundAudioManager();
    this.setData({ audioManager });
    audioManager.onPause(() => {
      this.setData({ playingId: -1 });
    });
  },
  togglePlay(event) {
    const { url, title, _id } = event.currentTarget.dataset.interview;
    if(!url){
      return wx.showToast({
        title: '音频文件不存在',
      })
    }
    const { audioManager, playingId } = this.data;
    if (playingId === _id) {
      audioManager.pause();
      this.setData({ playingId: -1 });
    } else {
      audioManager.title = title;
      audioManager.src = url;
      this.setData({ playingId: _id });
    }
  },
  stopAudio() {
    this.data.audioManager.stop();
  },
  onHide() {
    this.stopAudio();
  },
  onUnload() {
    this.stopAudio();
  },
});
